package javaMSCRM;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.apache.axis2.client.Options;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;

import com.microsoft.schemas.crm._2006.query.AllColumns;
import com.microsoft.schemas.crm._2007.coretypes.CrmAuthenticationToken;
import com.microsoft.schemas.crm._2007.webservices.CrmAuthenticationTokenDocument;
import com.microsoft.schemas.crm._2007.webservices.CrmServiceStub;
import com.microsoft.schemas.crm._2007.webservices.EntityName;
import com.microsoft.schemas.crm._2007.webservices.ExecuteDocument;
import com.microsoft.schemas.crm._2007.webservices.ExecuteDocument.Execute;
import com.microsoft.schemas.crm._2007.webservices.ExecuteResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.ExecuteResponseDocument.ExecuteResponse;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument.Retrieve;
import com.microsoft.schemas.crm._2007.webservices.RetrieveResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.RetrieveResponseDocument.RetrieveResponse;
import com.microsoft.schemas.crm._2007.webservices.Systemuser;
import com.microsoft.schemas.crm._2007.webservices.WhoAmIRequest;
import com.microsoft.schemas.crm._2007.webservices.WhoAmIResponse;
/**
 * @author Zoran IVANOV
 *
 */
public class Login implements ActionListener
{
   	JFrame appFrame;
   	JLabel usernameJL, passwordJL;
   	JTextField usernameJTF, passwordJTF;
   	JButton jbbLogin;
   	private static String username = "";
   	private static String password = "";
   	Container cPane;
   	
  //Get Settings
	static Settings Settings = new Settings();
	
	private static String host = Settings.getHost();
	private static int port =  Integer.parseInt(Settings.getPort());
	private static String domain = Settings.getDomain();
	private static String orgName = Settings.getOrganization();
	private String endpointURL = Settings.getEndpointURL();
	private String recordsPerPage = Settings.getRecordsPerPage();
	String UserId = "";
	JavaMSCRM JavaMSCRM = null;
   	
    /**
     * @param JavaMSCRM
     */
    public Login(JavaMSCRM JavaMSCRM)
    {
    	this.JavaMSCRM = JavaMSCRM;
        
        if(host.equals("") || (port == 0) || domain.equals("") || orgName.equals("") || endpointURL.equals("")){
        	//If bad settings open settings window
        	new Settings(true);
        }else{
        	 //Open Login Window
    	    createGUI();
        }
     
    }
    
    /**
     * @return String
     */
    public String getUserName(){
    	return username;
    }
    
    /**
     * @return String
     */
    public String getPassword(){
    	return password;
    }

   	/**
   	 * 
   	 */
   	public void createGUI(){

   		/*Create a frame, get its content pane and set layout*/
   		appFrame = new JFrame("Java MSCRM Login");
   		
     	// Place the Settings Frame at the center of the screen
   	    Toolkit tk = Toolkit.getDefaultToolkit ();
   	    Dimension screen = tk.getScreenSize ();
   	    int lx =  (int) (screen.getWidth ()  * 3/8);
   	    int ly =  (int) (screen.getHeight () * 3/8);
   	    appFrame.setLocation (lx,ly);

   		cPane = appFrame.getContentPane();
   		cPane.setLayout(new GridBagLayout());
   		
   		//Arrange components on contentPane and set Action Listeners to each JButton
   		arrangeComponents();
   		
   		Image img = Toolkit.getDefaultToolkit().getImage("C:/Users/Zoran/workspace/JavaMSCRM/src/icon.png");
   		appFrame.setIconImage(img);
   		appFrame.pack();
   		appFrame.setResizable(false);
   		appFrame.setVisible(true);
   	}
   	
   	/**
   	 * 
   	 */
   	public void arrangeComponents(){
   		usernameJL = new JLabel("Username: ");
   		passwordJL = new JLabel("Password: ");
   
   		usernameJTF = new JTextField(username);
   		passwordJTF = new JPasswordField(password);
   		
   		jbbLogin   = new JButton("Login");

   		/*add all initialized components to the container*/
   		GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
        gridBagConstraintsx01.gridx = 0;
        gridBagConstraintsx01.gridy = 0;
        gridBagConstraintsx01.insets = new Insets(5,5,5,5); 
        cPane.add(usernameJL, gridBagConstraintsx01);
        
        GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
        gridBagConstraintsx02.gridx = 1;
        gridBagConstraintsx02.insets = new Insets(5,5,5,5); 
        gridBagConstraintsx02.gridy = 0;
        gridBagConstraintsx02.gridwidth = 2;
        gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
        cPane.add(usernameJTF, gridBagConstraintsx02);
        
        GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
        gridBagConstraintsx03.gridx = 0;
        gridBagConstraintsx03.insets = new Insets(5,5,5,5); 
        gridBagConstraintsx03.gridy = 1;
        cPane.add(passwordJL, gridBagConstraintsx03);
        
        GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
        gridBagConstraintsx04.gridx = 1;
        gridBagConstraintsx04.insets = new Insets(5,5,5,5); 
        gridBagConstraintsx04.gridy = 1;
        gridBagConstraintsx04.gridwidth = 2;
        gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
        cPane.add(passwordJTF, gridBagConstraintsx04);
                
        GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
        gridBagConstraintsx09.gridx = 1;
        gridBagConstraintsx09.gridy = 4;
        gridBagConstraintsx09.insets = new Insets(5,5,5,100); 
        cPane.add(jbbLogin, gridBagConstraintsx09);
   		    	
   		jbbLogin.addActionListener(this);
   	}

   	/* (non-Javadoc)
   	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   	 */
   	public void actionPerformed (ActionEvent e){
   		if (e.getSource () == jbbLogin){
   			LoginUser();
        }
   	}
   	
   	/**
   	 * @param options
   	 */
   	private static void setOptions(Options options){ 
	    HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();  

	    ArrayList<String> authSchemes = new ArrayList<String>();  
	    authSchemes.add(HttpTransportProperties.Authenticator.NTLM);   
	    auth.setAuthSchemes(authSchemes);   

	    auth.setUsername(username);  
	    auth.setPassword(password);  
	    auth.setHost(host);  
	    auth.setPort(port);  
	    auth.setDomain(domain);  
	    auth.setPreemptiveAuthentication(false); //it doesnt matter...  
	    options.setProperty(HTTPConstants.AUTHENTICATE, auth);  
	    options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); //i think this is good.. not required though  
	}
   	 
     /**
     * Save Settings
     * @return String
     */
    public String LoginUser(){ 
	   	username = usernameJTF.getText();
	   	password = passwordJTF.getText();
	   	String UserFullName = "";

	   	if(username.equals("") || password.equals("")){
	   		JOptionPane.showMessageDialog(null, "All fields Are Mandatory.");
	   	}else{
	   		CrmServiceStub stub;   
			try {
				stub = new CrmServiceStub(endpointURL);  
		        setOptions(stub._getServiceClient().getOptions());  
		        
		        ExecuteDocument ed = ExecuteDocument.Factory.newInstance();
		        Execute exc = Execute.Factory.newInstance();
		        WhoAmIRequest wair = WhoAmIRequest.Factory.newInstance();
		        
		        exc.setRequest(wair);
		        ed.setExecute(exc);
		        			      
		        CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance();  
		        CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance();  
		        token.setAuthenticationType(0);     
		        token.setOrganizationName(orgName);  
		        catd.setCrmAuthenticationToken(token);  
		        
		        ExecuteResponseDocument erd = stub.Execute(ed, catd, null, null);
		        ExecuteResponse er = erd.getExecuteResponse();
		        WhoAmIResponse wairesponse = (WhoAmIResponse) er.getResponse();
		        UserId = wairesponse.getUserId();
		        
		        //Get user First and Last name
		        RetrieveDocument rd = RetrieveDocument.Factory.newInstance();  
		        Retrieve r = Retrieve.Factory.newInstance();  
		        
		        r.setEntityName(EntityName.SYSTEMUSER.toString());
		        r.setId(UserId);
		        r.setColumnSet(AllColumns.Factory.newInstance());
		        
		        rd.setRetrieve(r);	        
		        
		        RetrieveResponseDocument rrd = stub.Retrieve(rd,  catd, null, null);
		        RetrieveResponse rr = rrd.getRetrieveResponse();
		        Systemuser sr = (Systemuser) rr.getRetrieveResult();
		                
		        UserFullName = sr.getFullname();
		        
		        JavaMSCRM.HeaderUserFullName.setText(UserFullName+" ");
		        
		        JavaMSCRM.UserId = UserId;
		        
		        //Set Crm Service
		        JavaMSCRM.stub = new CrmServiceStub(endpointURL);  
		    	setOptions(JavaMSCRM.stub._getServiceClient().getOptions());
		    	
		    	//Set Authentication
		    	JavaMSCRM.catd = CrmAuthenticationTokenDocument.Factory.newInstance();  
		    	JavaMSCRM.token = CrmAuthenticationToken.Factory.newInstance();  
		    	JavaMSCRM.token.setAuthenticationType(0);     
		    	JavaMSCRM.token.setOrganizationName(orgName);  
		    	JavaMSCRM.catd.setCrmAuthenticationToken(JavaMSCRM.token); 
		    	JavaMSCRM.recordsPerPage = Integer.parseInt(recordsPerPage);
		    	
		    	JavaMSCRM.setVisible(true);
		        //Show Activities list by default
		        new Activities(JavaMSCRM);
		        //new JavaMSCRMAccounts(JavaMSCRM);
		        
		        appFrame.dispose();
		        
			}  
			catch (Exception e) {
				if(e.toString().endsWith("Unauthorized")){
					JOptionPane.showMessageDialog(null, "Wrong Username and Password!");
				}else if(e.toString().endsWith("AxisFault:"+host)){
					JOptionPane.showMessageDialog(null, "CRM Server unavailable!");
				}else{
					//e.printStackTrace();  
					JOptionPane.showMessageDialog(null, e.toString());
				}
			}
	    }
	   	return UserFullName;
     }

   }
